package com.samapp.map;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.baidu.mapapi.model.LatLng;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.samapp.MyApplication;
import com.samapp.R;
import com.samapp.base.BaseActivity;
import com.samapp.entity.Client;
import com.samapp.utils.json.GsonUtil;

public class ClientListActivity extends BaseActivity implements OnClickListener {

	private Button btnBack = null;
	private Button btnAdd = null;
	private PullToRefreshListView mPullToRefreshListView = null;
	private ClientAdapter mClientAdapter = null;
	private List<Client> mClients = new ArrayList<Client>();
	private MyApplication myApplication = MyApplication.getApplicationInstance();
	/** 当前页码 */
	private int pageNum = 0;
	/** 每页显示数量 */
	private int numPerPage = 20;
	/** 是否加载完所有记录 */
	private boolean isLoadAllRecord = false;
	/** 是否下拉操作 */
	boolean isPullDownToRefresh = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_client_list);
		init();
		getAllClient();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		getAllClient();
	}

	private void init() {
		initView();
		initPullToRefreshListView();
		initListener();
	}

	private void initView() {
		btnBack = (Button) findViewById(R.id.btn_back);
		btnAdd = (Button) findViewById(R.id.btn_add);
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pulltorefresh_client);
	}

	private void initPullToRefreshListView() {
		mPullToRefreshListView.setMode(PullToRefreshListView.Mode.BOTH);
		// 上拉
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载更多");
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setReleaseLabel("放开加载");
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
		// 下拉
		mPullToRefreshListView.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新");
		mPullToRefreshListView.getLoadingLayoutProxy(true, false).setReleaseLabel("放开加载");
		mPullToRefreshListView.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在加载...");
		mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				isPullDownToRefresh = true;
				pageNum = 0;// 返回显示第0页
				getAllClient();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				isPullDownToRefresh = false;
				pageNum = pageNum + 1;// 下一页
				getAllClient();
			}
		});
		mClientAdapter = new ClientAdapter(ClientListActivity.this, mClients);
		mPullToRefreshListView.setAdapter(mClientAdapter);
	}

	private void initListener() {
		btnBack.setOnClickListener(this);
		btnAdd.setOnClickListener(this);
		mPullToRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Client client = mClients.get(position-1);
				myApplication.curCenPT = new LatLng(Double.parseDouble(client.getLatitude()), Double.parseDouble(client.getLongitude()));
				btnBack.performClick();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			skip(ClientDistributionActivity.class);
			break;
		case R.id.btn_add:
			skip(AddClientActivity.class);
			break;
		}
	}

	/**
	 * 获取所有客户
	 */
	private void getAllClient() {
		showLoadingDialog("正在加载客户列表……");
		String url = myApplication.url + "listClient.htm";
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("accessToken", "5C9.yx0S");
		params.addQueryStringParameter("pageNum", "" + pageNum);
		params.addQueryStringParameter("numPerPage", "" + numPerPage);
		new HttpUtils().send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.i("Http", responseInfo.result);
				// {"code":"0","list":[]}
				try {
					JSONObject jsonObject = new JSONObject(responseInfo.result);
					if (jsonObject.has("code") && "0".equals(jsonObject.getString("code"))) {
						List<Client> mClientsTemp = GsonUtil.getGson().fromJson(jsonObject.getString("list"), new TypeToken<List<Client>>() {
						}.getType());
						if (mClientsTemp.size() < numPerPage) {
							isLoadAllRecord = true;
						} else {
							isLoadAllRecord = false;
						}
						if (isPullDownToRefresh) {
							mClients.clear();
						}
						for (Client mClient : mClientsTemp) {
							mClients.add(mClient);
						}
						onRefreshComplete();
					} else {
						showToast(jsonObject.getString("msg"));
					}
					dismissLoadingDialog();
				} catch (Exception e) {
					e.printStackTrace();
					dismissLoadingDialog();
				}
			}

			@Override
			public void onFailure(HttpException e, String arg1) {
				e.printStackTrace();
				dismissLoadingDialog();
			}
		});
	}

	/** 跳转页面 */
	private void skip(Class<?> cls) {
		Intent intent = new Intent(this, cls);
		startActivity(intent);
		finish();
	}

	private void onRefreshComplete() {
		if (isLoadAllRecord) {
			showToast("加载完全部数据！");
		}
		mClientAdapter.notifyDataSetChanged();
		mPullToRefreshListView.onRefreshComplete();
	}
}
